package com.example.project7.repository;

import android.content.Context;
import android.util.Log;

import com.example.project7.model.User;
import com.example.project7.model.UserListResponse;
import com.example.project7.utils.ApiResponse;
import com.example.project7.utils.HttpUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UserRepository {
    private static final String TAG = "UserRepository";
    private static final String BASE_URL = "https://reqres.in/api";
    private static final String USERS_URL = BASE_URL + "/users";

    private Context context;

    public UserRepository(Context context) {
        this.context = context;
    }

    /**
     * 获取用户列表
     *
     * @param page 页码
     * @return ApiResponse对象
     */
    public ApiResponse<List<User>> getUsers(int page) {
        try {
            String url = USERS_URL + "?delay=3&page=" + page; // 添加delay参数模拟网络延迟
            ApiResponse<UserListResponse> response = HttpUtil.get(url, null, UserListResponse.class);
            
            if (response.isSuccess()) {
                List<User> users = response.getData().getData();
                if (users != null) {
                    // 按用户ID升序排列
                    Collections.sort(users, (u1, u2) -> Integer.compare(u1.getId(), u2.getId()));
                    return new ApiResponse<>(true, users, null);
                } else {
                    return new ApiResponse<>(true, new ArrayList<>(), null);
                }
            } else {
                return new ApiResponse<>(false, null, response.getErrorMessage());
            }
        } catch (Exception e) {
            Log.e(TAG, "获取用户列表时发生异常", e);
            return new ApiResponse<>(false, null, "网络请求失败: " + e.getMessage());
        }
    }
}